package com.controller;


import com.utils.JSONResult;
import com.utils.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Random;

/**
 * @Description 公共模块（文件上传）
 * @Author wzl
 * @Date 2017/4/28
 **/
@Controller
@RequestMapping("/upload")
public class UploaderController {

    //上传文件
    @RequestMapping(value = "/toFileUploader")
    public ModelAndView toFileUploader() {
        ModelAndView mv =new ModelAndView("uploadFile");
        return mv;
    }


    /**
     * 上传文件
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/uploadFile",method = RequestMethod.POST)
    @ResponseBody
    private JSONResult uploadFile(@RequestParam(value="file",required=false) MultipartFile file,HttpServletRequest request) throws IOException {
        JSONResult jsonResult= new JSONResult();
        String path=request.getSession().getServletContext().getRealPath("/upload");//文件上传服务器地址
        String fileName=file.getOriginalFilename();//获取上传文件名
        String suffix = fileName.substring(fileName.lastIndexOf("."));//获取文件后缀名
        Random random = new Random();
        int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;
        String newFileName = StringUtils.getNowTime().toString()+rannum+suffix;//重命名文件
        File targetFile=new File(path,newFileName);//创建文件夹存储文件
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        file.transferTo(targetFile);
        String newPath = "/upload/"+ newFileName;//服务器返回地址
        jsonResult.setUrl(newPath);
        return jsonResult;
    }

}
